package com.xky.ui.module.customersManagement.add;

import com.xky.utils.DBUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.sql.*;

public class AddCustomers extends JFrame {
    private JPanel jPanel1, jPanel2, jPanel3;
    private JTextField[] textFields;
    private JComboBox<String> isActiveComboBox;
    public AddCustomers() {
        setTitle("添加客户信息");
        setSize(520, 750);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    private void init() {
        setLayout(new BorderLayout());

        // 顶部标题面板 - 添加渐变背景
        jPanel2 = new JPanel(new GridBagLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // 创建渐变色背景
                GradientPaint gradient = new GradientPaint(
                    0, 0, new Color(48, 57, 82), 
                    getWidth(), getHeight(), new Color(38, 47, 72)
                );
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
        };
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0;

        JLabel titleLabel = new JLabel("添加客户信息");
        titleLabel.setFont(new Font("楷体", Font.BOLD, 30));
        titleLabel.setForeground(Color.WHITE);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(20, 0, 20, 0);
        jPanel2.add(titleLabel, gbc);
        add(jPanel2, BorderLayout.NORTH);

        // 主输入面板 - 添加圆角和阴影
        jPanel1 = new JPanel(new GridBagLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // 绘制圆角背景
                int cornerRadius = 15;
                g2d.setColor(getBackground());
                g2d.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), cornerRadius, cornerRadius));
                
                // 添加轻微阴影效果
                g2d.setColor(new Color(0, 0, 0, 20));
                for (int i = 0; i < 3; i++) {
                    g2d.drawRoundRect(i, i, getWidth() - 2*i - 1, getHeight() - 2*i - 1, cornerRadius, cornerRadius);
                }
                
                g2d.dispose();
            }
        };
        
        JLabel[] labels = new JLabel[]{
                new JLabel("客户编码 *"),
                new JLabel("客户名称 *"),
                new JLabel("联系人 *"),
                new JLabel("联系电话 *"),
                new JLabel("电子邮箱 *"),
                new JLabel("联系地址 *"),
                new JLabel("信用额度 *"),
                new JLabel("是否有效 *"),
        };

        textFields = new JTextField[7]; // 减少一个，因为最后一个是下拉框
        Font font = new Font("微软雅黑", Font.PLAIN, 16);

        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i + 1;
            gbc.insets = new Insets(10, 20, 10, 10);
            labels[i].setFont(font);
            jPanel1.add(labels[i], gbc);

            if (i < 7) {
                textFields[i] = new JTextField(20);
                textFields[i].setFont(font);
                textFields[i].setPreferredSize(new Dimension(200, 35));
                // 添加圆角边框
                textFields[i].setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(200, 200, 200)),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)
                ));
                gbc.gridx = 1;
                jPanel1.add(textFields[i], gbc);
            } else {
                // 为"是否有效"创建下拉框
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(font);
                isActiveComboBox.setPreferredSize(new Dimension(200, 35));
                gbc.gridx = 1;
                jPanel1.add(isActiveComboBox, gbc);
            }
        }

        // 添加字段说明标签
        JLabel noteLabel = new JLabel("<html><body style='width: 350px'>" +
                "<p style='color: #666666;'>注意：带 * 的字段为必填项</p>" +
                "</body></html>");
        noteLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        gbc.gridx = 0;
        gbc.gridy = labels.length+1;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(20, 20, 10, 10);
        jPanel1.add(noteLabel, gbc);

        // 添加边框和背景色
        jPanel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        jPanel1.setBackground(new Color(245, 245, 245));

        add(jPanel1, BorderLayout.CENTER);

        // 底部按钮面板
        jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 20));
        JButton submitButton = createStyledButton("提交", new Color(41, 128, 185));
        submitButton.setPreferredSize(new Dimension(120, 40));

        JButton resetButton = createStyledButton("重置", new Color(180, 180, 180));
        resetButton.setPreferredSize(new Dimension(120, 40));

        jPanel3.add(submitButton);
        jPanel3.add(resetButton);
        jPanel3.setBackground(new Color(240, 240, 240));

        add(jPanel3, BorderLayout.SOUTH);

        // 提交按钮事件
        submitButton.addActionListener(e -> {
            try {
                // 获取并验证输入
                String customerCode = textFields[0].getText().trim();
                String customerName = textFields[1].getText().trim();
                String contactPerson = textFields[2].getText().trim();
                String contactPhone = textFields[3].getText().trim();
                String email = textFields[4].getText().trim();
                String address = textFields[5].getText().trim();
                Double creditLimit = parseDoubleField(textFields[6].getText().trim(), "信用额度");
                Boolean isActive = isActiveComboBox.getSelectedItem().equals("是");

                // 输入验证
                if (!validateInputs(customerCode, customerName, contactPerson,
                                   contactPhone, email, address, creditLimit)) {
                    return;
                }

                // 添加客户记录
                if (addCustomer(customerCode, customerName, contactPerson,
                              contactPhone, email, address, creditLimit, isActive)) {
                    JOptionPane.showMessageDialog(this, "客户信息添加成功！",
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "客户信息添加失败！",
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        });

        // 重置按钮事件
        resetButton.addActionListener(_ -> {
            for (JTextField field : textFields) {
                field.setText("");
            }
            isActiveComboBox.setSelectedIndex(0);
        });
    }
    
    private JButton createStyledButton(String text, Color color) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // 创建渐变背景
                GradientPaint gradient = new GradientPaint(
                    0, 0, color, 
                    0, getHeight(), color.darker()
                );
                g2d.setPaint(gradient);
                
                // 绘制圆角矩形
                g2d.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 12, 12));
                
                g2d.dispose();
                super.paintComponent(g);
            }
        };
        
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setForeground(Color.WHITE);
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        
        // 添加鼠标悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                button.setCursor(new Cursor(Cursor.HAND_CURSOR));
                if (text.equals("提交")) {
                    button.setForeground(new Color(220, 255, 255));
                } else {
                    button.setForeground(new Color(240, 240, 240));
                }
            }

            public void mouseExited(MouseEvent evt) {
                button.setForeground(Color.WHITE);
            }
        });
        
        return button;
    }

    private Double parseDoubleField(String text, String fieldName) throws NumberFormatException {
        if (text.isEmpty()) {
            return 0.0; // 允许为空，默认为0
        }
        try {
            return Double.parseDouble(text);
        } catch (NumberFormatException e) {
            throw new NumberFormatException(fieldName + "必须是有效的数字");
        }
    }

    private boolean validateInputs(String customerCode,
                                   String customerName, String contactPerson,
                                   String contactPhone, String email, 
                                   String address, Double creditLimit) {

        if (customerCode.isEmpty()) {
            showValidationError("客户编码不能为空");
            return false;
        }

        if (customerName.isEmpty()) {
            showValidationError("客户名称不能为空");
            return false;
        }

        if (contactPerson.isEmpty()) {
            showValidationError("联系人不能为空");
            return false;
        }

        if (contactPhone.isEmpty()) {
            showValidationError("联系电话不能为空");
            return false;
        }
        
        // 简单的电子邮箱格式验证
        String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
        if (email.matches(EMAIL_REGEX)) {
            showValidationError("电子邮箱格式不正确");
            return false;
        }

        // 检查客户编码是否已存在
        if (isCustomerCodeExists(customerCode)) {
            showValidationError("客户编码已存在，请使用其他编码");
            return false;
        }

        return true;
    }

    private boolean isCustomerCodeExists(String customerCode) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            String sql = "SELECT COUNT(*) FROM customers WHERE customer_code = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, customerCode);
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                return resultSet.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
        return false;
    }

    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入验证错误", JOptionPane.WARNING_MESSAGE);
    }

    private boolean addCustomer(String customerCode,
                               String customerName, String contactPerson,
                               String contactPhone, String email, 
                               String address, Double creditLimit, Boolean isActive) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            connection.setAutoCommit(false);

            String sql = "INSERT INTO customers(customer_code, customer_name, " +
                    "contact_person, phone, email, address, credit_limit, " +
                    "is_active, created_time, updated_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";

            preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1, customerCode);
            preparedStatement.setString(2, customerName);
            preparedStatement.setString(3, contactPerson);
            preparedStatement.setString(4, contactPhone);
            preparedStatement.setString(5, email);
            preparedStatement.setString(6, address);
            preparedStatement.setDouble(7, creditLimit);
            preparedStatement.setBoolean(8, isActive);

            int affectedRows = preparedStatement.executeUpdate();
            connection.commit();

            if (affectedRows > 0) {
                System.out.println("受影响的行数为" + affectedRows + "，添加成功！");
                return true;
            } else {
                System.out.println("受影响的行数为" + affectedRows + "，添加失败！");
                return false;
            }
        } catch (SQLException e) {
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new AddCustomers();
        });
    }
}
